<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <!-- 用户的头像 -->
          <van-image
            round
            class="avatar"
            :src="userProfile.photo"
            @click="$refs.fileRef.click()"
          />
          <!-- 文件选择框 -->
          <input
            type="file"
            accept="image/*"
            @change="onFileChange"
            v-show="false"
            ref="fileRef"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="userProfile.name"
        @click="onNameCellClick"
      />
      <van-cell
        title="生日"
        is-link
        :value="userProfile.birthday"
        @click="onBirthCellClick"
      />
    </van-cell-group>
    <!-- 修改用户名称的对话框 -->
    <van-dialog
      v-model="showNameDialog"
      title="修改名称"
      show-cancel-button
      :before-close="beforeClose"
    >
      <!-- input-align 文本横向的对其方式 -->
      <van-field
        v-model.trim="name"
        placeholder="请输入用户名"
        input-align="center"
        maxlength="7"
        ref="nameRef"
      />
    </van-dialog>
    <!-- 修改生日的动作面板 -->
    <van-action-sheet v-model="showBirthSheet">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择出生日期"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthSheet = false"
        @confirm="updateBirthday"
      />
    </van-action-sheet>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { updateUserProfileAPI, updateUserAvatarAPI } from "../api/userAPI.js";
import dayjs from "dayjs";
export default {
  name: "UserEdit",
  data() {
    return {
      showNameDialog: false,
      showBirthSheet: false,
      name: "",
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(2050, 11, 31),
      currentDate: new Date(),
    };
  },
  methods: {
    ...mapActions(["initUserProfile"]),
    onNameCellClick() {
      this, (name = this.userProfile.name);
      this.showNameDialog = true;
      this.$nextTick(() => {
        this.$refs.nameRef.focus();
      });
    },
    beforeClose(action, done) {
      if (action === "cancal") {
        return done();
      }
      if (this.name === "" || this.name.length > 7) {
        this.$notify({
          type: "warning",
          message: "名称的长度为1-7个字符",
          duration: 2000,
        });
        this.$refs.nameRef.focus();
        return done(false);
      }

      this.updateName(done);
    },
    async updateName(done) {
      const { data: res } = await updateUserProfileAPI({ name: this.name });
      if (res.message === "OK") {
        done();
        this.initUserProfile();
        this.$$notify({
          type: "success",
          messgae: "名称更新成功！",
          duration: 2000,
        });
      }
    },
    onBirthCellClick() {
      this.currentDate = this.userProfile.birthday
        ? new Date(this.userProfile.birthday)
        : new Date();
      this.showBirthSheet = true;
    },
    async updateBirthday(value) {
      this.showBirthSheet = false;
      const dateStr = dayjs(value).format("YYYY-MM-DD");
      const { data: res } = await updateUserProfileAPI({ birthday: dateStr });

      if (res.messgae === "OK") {
        this.initUserProfile();
        this.$notify({
          type: "success",
          messgae: "生日修改成功！",
          duration: 2000,
        });
      }
    },
    // 选中的文件发生了变化
    async onFileChange(e) {
      // 获取到用户选择的文件列表
      const files = e.currentTarget.files;
      // 如果没有选择任何文件，则不执行后续的业务逻辑
      if (files.length === 0) return;

      // 1.1 创建 FormData 的对象
      const fd = new FormData();
      // 1.2 向 fd 中追加数据项
      fd.append("photo", files[0]);

      // 2. 调用 API 接口，更新头像
      const { data: res } = await updateUserAvatarAPI(fd);
      if (res.message === "OK") {
        // 2.1 更新用户的简介信息
        this.initUserProfile();
        // 2.2 提示用户更新成功
        this.$notify({
          type: "success",
          message: "更新头像成功！",
          duration: 2000,
        });
      }
    },
  },
  computed: {
    ...mapState(["userProfile"]),
  },
  created() {
    this.initUserProfile();
  },
};
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
}

.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>